package ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import entities.Hotel;

/**
 * Session Bean implementation class HotelMgrBean
 */
@Stateless
public class HotelMgrBean implements HotelMgrBeanLocal {

	@PersistenceContext
    private EntityManager em;

	@Override
	public void aggiungi(HotelDTO hotel){
		Hotel nuovo = new Hotel(hotel);
		em.persist(nuovo);
	}
	
	@Override
	public void modifica(HotelDTO hotel, int indice){
		Query q = em.createNamedQuery("Hotel.MODIFICA");
		q.setParameter("id", indice);
		q.setParameter("nome", hotel.getNome());
		q.setParameter("numeroStelle", hotel.getNumeroStelle());
		q.setParameter("prezzo", hotel.getPrezzo());
		q.executeUpdate();
	}
	
	private Hotel trova(int id) {
    	return em.find(Hotel.class, id);
    }
	
	public List<?> getHotel() {
    	return em.createNamedQuery("Hotel.FIND_ALL", Hotel.class).getResultList();
    }

	public void elimina(int indice){
		Query q = em.createNamedQuery("Hotel.CANCELLA");
		q.setParameter("id", indice);
		q.executeUpdate();
	}
	
	public HotelDTO getHotelDTO(int indice) {
		Hotel hotel = trova(indice);
		HotelDTO hotelDTO = convertToDTO(hotel);
		return hotelDTO;
	}

	 public static HotelDTO convertToDTO(Hotel hotel) {
		HotelDTO hotelDTO = new HotelDTO();
		hotelDTO.setIdHotel(hotel.getIdHotel());
		hotelDTO.setNome(hotel.getNome());
		hotelDTO.setNumeroStelle(hotel.getNumeroStelle());
		hotelDTO.setPrezzo(hotel.getPrezzo());
		return hotelDTO;
	}
	 
	 public List<HotelDTO> getListaHotelDTO(){
		 List<Hotel> hotel= em.createNamedQuery("Hotel.FIND_ALL", Hotel.class).getResultList();
		 List<HotelDTO> hotelDTO = new ArrayList<>();
		
		 for(Hotel h: hotel){
			 hotelDTO.add(convertToDTO(h));
		 }
		 return hotelDTO;
	 }
	 
	 public static List<HotelDTO> convertToDTOLista(List<Hotel> hotelList) {
		List<HotelDTO> hotelDTOList = new ArrayList<HotelDTO>();
		for(Hotel h: hotelList){
			hotelDTOList.add(convertToDTO(h));
		}
		return hotelDTOList;
	}
}